﻿using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

namespace Md.Api.DDD;
/// <summary>
/// 邮箱帮助类
/// </summary>
public class EmailHelp
{
    /// <summary>
    /// 创建邮箱内容
    /// </summary>
    /// <param name="_fromEmail">发送邮箱</param>
    /// <param name="_toEmail">接收邮箱</param>
    /// <param name="_subject">主题</param>
    /// <param name="_body">内容</param>
    /// <returns>MimeMessage</returns>
    public static MimeMessage CreateSimpleMessage(string _fromEmail, string _toEmail, string _subject, string _body)
    {
        try
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(_fromEmail, _fromEmail));

            message.To.Add(new MailboxAddress(_toEmail, _toEmail));

            message.Subject = _subject;

            var builder = new BodyBuilder();

            builder.HtmlBody = string.Format(_body);

            message.Body = builder.ToMessageBody();

            return message;
        }
        catch (Exception ex)
        {
            throw new AggregateException(ex.Message);
        }
    }

    /// <summary>
    /// 发送邮件
    /// </summary>
    /// <param name="_fromEmail">发送邮箱</param>
    /// <param name="_toEmail">接收邮箱</param>
    /// <param name="_subject">主题</param>
    /// <param name="_body">内容</param>
    /// <returns>bool</returns>
    public static bool SendEmail(string _fromEmail, string _toEmail, string _subject, string _body)
    {
        var result = false;
        try
        {
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.MessageSent += (sender, args) => {
                    // Console.WriteLine("发送邮件状态：" + args.Response);
                };
                smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true;
                smtpClient.Connect(JsonConfig.JsonRead("MdEmail:Host"), Convert.ToInt32(JsonConfig.JsonRead("MdEmail:Port")), true);
                smtpClient.Authenticate(JsonConfig.JsonRead("MdEmail:AuthEmail"), JsonConfig.JsonRead("MdEmail:AuthPwd"));
                smtpClient.Send(CreateSimpleMessage(_fromEmail, _toEmail, _subject, _body));
                smtpClient.DisconnectAsync(true);

                result = true;
            }
        }
        catch (Exception ex)
        {
            result = false;
            throw new AggregateException(ex.Message);
        }

        return result;
    }
}

